import { ISelectGroupState } from '@/entrypoints/home/components/SelectGroup'
import { Form, Message, Upload } from '@arco-design/web-react'
import { UploadItem } from '@arco-design/web-react/es/Upload'
import React from 'react'

export interface IImFromFileProps {
    // 预览数据
    onPreview?: (
        items: IListItem[],
        recommendGroupOptions?: Partial<ISelectGroupState>,
    ) => void
}

const ImFromFile: React.FC<IImFromFileProps> = ({ onPreview }) => {
    // 文件变化
    const handleFileChange = (_fileList: UploadItem[], file: UploadItem) => {
        if (!file.originFile) return
        const reader = new FileReader()
        reader.onload = (event) => {
            const json = JSON.parse(event.target?.result as string)
            if (!json?.list?.length) {
                Message.error('文件格式错误')
                return
            }
            onPreview?.(json.list, {
                addGroup: false,
            })
        }
        reader.readAsText(file.originFile)
    }

    return (
        <div>
            {/* 上传文件 */}
            <Form.Item label='文件' required>
                <Upload
                    autoUpload={false}
                    multiple={false}
                    showUploadList={false}
                    onChange={handleFileChange}
                    accept={'.json'}
                />
            </Form.Item>
        </div>
    )
}

export default ImFromFile
